$(function(){
	//initMenuTree();
	initConfiguration();
	initIndexTab();
	initMenuTree();
	$('#side-menu').metisMenu();
	logout();
	changePwd();
	changePwdSubmit();
	checkPasswordExpire();
});

/**
 * 页面加载完毕后添加首页
 * @returns
 */
function initIndexTab(){
	$.ajax({
		type : 'GET',
		url : 'initHomeMenu',
		data :  null,
		cache : false,
		async : false,
		success : function(obj) {
			var ret = obj;
			// console.info('home ret.data.uri：' + ret.data.uri);
			if(ret.data) {
				// var indexUrl = "/yfdw-common-notice/fcbp/yfdw-common-notice/index.html#/message";
				var indexUrl = ret.data.uri;
			    console.info('主页加载完毕。。。');
			    $('#j_iframe').attr('src', indexUrl);
			} else {
				console.info('主页加载失败，未获取到配置!');
			}
		},
		error : function() {
			layer.msg('主页菜单加载失败!'); 
		}
	});
}
var mix_num=6;
var max_num=18;
// 是否复杂密码
var pwd_complex_open=true;
function changePwd(){
	// $(".fa-eye").hide();
	$(".fa-eye-slash").hide();
	$(".fa-eye").eq(0).on('click',function () {
		$("#orginpassword").attr("type","text");
		$(".fa-eye").eq(0).hide();
		$(".fa-eye-slash").eq(0).show();
	})
	$(".fa-eye").eq(1).on('click',function () {
		$("#newpassword").attr("type","text")
		$(".fa-eye").eq(1).hide();
		$(".fa-eye-slash").eq(1).show();
	})
	$(".fa-eye").eq(2).on('click',function () {
		$("#confirmpassword").attr("type","text")
		$(".fa-eye").eq(2).hide();
		$(".fa-eye-slash").eq(2).show();
	})
	$(".fa-eye-slash").eq(0).on('click',function () {
		$("#orginpassword").attr("type","password");
		$(".fa-eye").eq(0).show();
		$(".fa-eye-slash").eq(0).hide();
	})
	$(".fa-eye-slash").eq(1).on('click',function () {
		$("#newpassword").attr("type","password");
		$(".fa-eye").eq(1).show();
		$(".fa-eye-slash").eq(1).hide();
	})
	$(".fa-eye-slash").eq(2).on('click',function () {
		$("#confirmpassword").attr("type","password");
		$(".fa-eye").eq(2).show();
		$(".fa-eye-slash").eq(2).hide();
	})
	$('#changePwd').on('click',function(){
		initConfiguration();
		$('#orginpassword').val('');
		$('#newpassword').val('');
		$('#confirmpassword').val('');
    	$("#passwordMsg").show();
    	$("#passwordErr").hide();
    	$("#passwordDiff").hide();
		$('#myModal').modal();
		//密码长度设置提示信息的渲染
		if(pwd_complex_open){
			$("#passwordMsg").html("长度为"+mix_num+"-"+max_num+"位，至少1个大写字母，1个小写字母，1个数字和1个特殊字符");
			$("#passwordErr").html("密码格式错误(长度为"+mix_num+"-"+max_num+"位，至少1个大写字母，1个小写字母，1个数字和1个特殊字符)");
		}else{
			$("#passwordMsg").html("");
			$("#passwordErr").html("");
		}
		//隐藏下拉选项显示
	    $('#right-sidebar').removeClass('sidebar-open');
		$('#perul li:gt(0)').slideToggle();
	})
	$('#newpassword').on('keyup', function() {
	    // var r = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,18}$/;
		if(pwd_complex_open){
			var r=eval('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{'+mix_num+','+max_num+'}$/');
			if (!r.test($('#newpassword').val())){
				$("#passwordMsg").hide();
				$("#passwordErr").show();
			} else {
				$("#passwordMsg").show();
				$("#passwordErr").hide();
			}
		}
	    if ($('#newpassword').val() != $('#confirmpassword').val() && $('#confirmpassword').val() != ''){
	    	$("#passwordDiff").show();
	    } else {
	    	$("#passwordDiff").hide();
	    }
	});
	$('#confirmpassword').on('keyup', function() {
	    if ($('#newpassword').val() != $('#confirmpassword').val()){
	    	$("#passwordDiff").show();
	    } else {
	    	$("#passwordDiff").hide();
	    }
	});
}

function changePwdSubmit () {
	// var r = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{mix_num,max_num}$/;
	var r=eval('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{'+mix_num+','+max_num+'}$/');
	$('#changePwdSubmit').on('click',function(){
		if ($('#orginpassword').val() != '' && ((r.test($('#newpassword').val()) && pwd_complex_open) || !pwd_complex_open ) &&
		  $('#newpassword').val() == $('#confirmpassword').val()) {
			var modulus = "00f428e2d928aa802b0ad018a895a4d913f1d22eeacc464eca7ecb480d877001911992d863d29045a56aef761caffc80f88157e375341f84b573eeab2dcb33431dcb5ea973394577d210603246c030f1b529869333e86117f3a81e3faa1c419844b7b5bc76d91dfa1861343f3e7064c18d1e1673d23f625f56e4095f816fc39b8d";
			var exponent = "010001";
			var key = RSAUtils.getKeyPair(exponent, '', modulus);
			$.ajax({
			    data: {
			        'userName': username,
			        'oldPassword': RSAUtils.encryptedString(key, $('#orginpassword').val()),
			        'newPassword': RSAUtils.encryptedString(key, $('#newpassword').val())
			    },
			    type : "POST",
			    dataType: 'json',
			    url: "changePassword",
			    success: function(data) {
			        if(data.yhRspType == 'ERROR') {
			        	layer.msg(data.msg);
			        } else {
			        	layer.msg('修改密码成功,请重新登录系统');
			        	setTimeout(function () {
			        		window.location.href = "logout"
			            },1500);
			        }
			    }
			})
		} else {
			layer.msg("表单验证失败!");
		}
	})	
}

function logout(){
	$('#logout').on('click',function(){
		layer.confirm("确认退出系统吗?", {
			shade : false,
			btn : [ '确认', '取消' ]
		}, function() {
			var scr = document.createElement("iframe");      //创建iframe      
			var fineReportUrl = "http://[[${config.fineReportUrl}]]?op=fs_load&cmd=ssout";
			scr.src = fineReportUrl;   //将帆软报表登出地址指向此iframe  
            if (scr.attachEvent) {       //判断是否为ie浏览器    
                   scr.attachEvent("onload", function(){                    //如果为ie浏览器则页面加载完成后立即执行    
                   });    
               } else {    
                  scr.onload = function(){              //其他浏览器则重新加载onload事件    
               };    
            }    
            document.getElementsByTagName("head")[0].appendChild(scr);    //将iframe标签嵌入到head中 
			window.location.href = "logout";
		});
	});
}

/**
 * 初始化菜单
 * @returns
 */
function initMenuTree() {
	var params = {
			userName:username
	};
	$.ajax({
		type : 'GET',
		url : 'initMenu',
		data :  params,
		cache : false,
		async : false,
		success : function(obj) {
			console.info(obj);
			var ret = obj;//JSON.parse(obj);
			console.info('转为json数据：' + ret);
			console.info('转为ret.msg数据：' + ret.data);
			var result = ret.data;//JSON.parse(ret.data);
			var html = "";
			var html2 = "";
			/*for (var i in result.tree) {
				console.info('数据：' + result.tree[i].id + " " + result.tree[i].name);
				html += "<li id = ' "+result.tree[i].id +"'>"
						+ "<a href='#'>"
						+ "<i class = 'fa fa fa-bar-chart-o'></i>"
						+ "<span class='nav-label'>"+result.tree[i].name+"</span>"
						+ "<span class='fa arrow'></span>"
		                + "</a></li>"
			}*/
			for (var i in result.tree) {
				console.info('数据：' + result.tree[i].id + " " + result.tree[i].name + ":" + result.tree[i].ico);
				
				html += "<li id = ' "+result.tree[i].id +"'>"
						+ "<a href='#'>"
						+ "<i class = 'fa fa-"+result.tree[i].ico+" fa-fw fa-lg'></i>"
						+ "<span class='nav-label'>"+result.tree[i].name+"</span>"
						+ "<span class='fa arrow'></span>"
		                + "</a>";
				
		        var children = result.tree[i].children;
				if(children){
					for (var j in children) {
						console.info('数据库获取URI:' + children[j].uri);
						var children3 = children[j].children;
						console.info('获取的三级菜单：' + children3);
						if(children3){
							var html3 = "";
							html2 = "<a href='#'>" 
								+ "<i class = 'fa fa-"+children[j].ico+" fa-fw'></i>"
								+ "<span class='nav-label'>"+children[j].name+"</span>"
							+ "<span class='fa arrow'></span></a>"
							+ "<ul class='nav nav-third-level'>";
							for(var k in children3){
								html3 += "<li>"
	                            + "<a class='J_menuItem' href='"+children3[k].uri+"'><i class = 'fa fa-"+children3[k].ico+" fa-fw'></i>"
								+ "<span class='nav-label'>"+children3[k].name+"</span></a>"
	                            + "</li>"
							}
							html2 +=  html3 + "</ul>";
							console.info('拼接3级菜单' + html2);
						}else{
							html2 = "<a class='J_menuItem' href='"+children[j].uri+"'><i class = 'fa fa-"+children[j].ico+" fa-fw'></i>"
								+ "<span class='nav-label'>"+children[j].name+"</span></a>"
						}
						
						html +=  "<ul class='nav nav-second-level'>"
                             + "<li>"
                             + html2
                             + "</li>"
							 + "</ul>"
					}
				}
				html += "</li>";
				$('#side-menu').append(html);
				html = "";
			}
		},
		error : function() {
			layer.msg('用户菜单加载失败,请重新登录!'); 
		}
	});

}

// 密码框关闭事件
$('#myModal').on('hidden.bs.modal', function (e) {
	console.info("修改框关闭");
	checkPasswordExpire();
})

/**
 * 检查密码过期
 * @returns
 */
function checkPasswordExpire(){
	console.info('开始检查密码是否过期.');
	var params = {
			userName:username,
			password:'111111'
	};
	$.ajax({
		type : 'GET',
		url : 'checkPasswordExpire',
		data :  params,
		cache : false,
		async : false,
		success : function(obj) {
			var ret = obj;
			// console.info('checkPasswordExpire ret.data：' + ret.data);
			if(ret.yhRspType=='SUCC' && ret.msg!='') {
				if(ret.data=="1"){
					layer.msg(ret.msg);
					console.info("修改密码弹出框弹出");
					$('#myModal').modal('show')
				}else{
					layer.msg(ret.msg);
				}
			} else if(ret.yhRspType=='ERROR') {
				console.info('检查密码过期出现错误：'+ret.msg);
			} else {
				console.info('密码未过期!');
			}
		},
		error : function() {
			console.info('检查密码过期，出现错误!');
		}
	});
}

function loadMinAndMaxNumberByCode(code) {
	$.ajax({
		type : 'GET',
		// url : '/fcbp-entry-web/ycmp/basicparameter/configuration/value/'+code,
		url : 'ycmp/basicparameter/configuration/value/'+code,
		cache : false,
		async : true,
		success : function(obj) {
			if(obj!=null && obj.data!=null){
				console.log(obj.data);
				if(code=="pwd_min_num"){
					console.info('密码最小长度为：'+obj.data);
					mix_num=parseInt(obj.data,  10);
				}else if(code=="pwd_max_num"){
					console.info('密码最大长度为：'+obj.data);
					max_num=parseInt(obj.data,  10);
				}else if(code=="pwd_complex_open"){
					pwd_complex_open=(obj.data=='1');
				}
			}
		},
		error : function() {
			console.info('请求控制开关，出现错误!');
		}
	});
}
function initConfiguration(){
	loadMinAndMaxNumberByCode("pwd_min_num");
	loadMinAndMaxNumberByCode("pwd_max_num");
	loadMinAndMaxNumberByCode("pwd_complex_open");
}


